const fs = require('fs');
const request = require("request-promise-native");
const { execSync } = require("child_process");
const { resolve } = require("path");

class LibraryService {
  async searchLibrary(name) {
    console.log(name);
    const url = "https://www.npmjs.com/search/suggestions?q=" + name;
    let opts = {
      url,
      method: "GET",
      json: true,
    };

    let body = await request(opts);
    return body;
  }

  async installLibrary(name, repository) {
    try {
      // 1. 在project项目下安装
      await execSync(`cd ../temp && npm info ${name}`);
      
      // 2. 打包成system模块
      // 获取入口
      const packageJsonPath = resolve(__dirname, `../../temp/node_modules/${name}`);
      console.log('packageJsonPath -> ', packageJsonPath);
      const packageJsonStr = fs.readFileSync(packageJsonPath.concat('/package.json'), 'utf-8');
      const packageJson = JSON.parse(packageJsonStr);
      const entry = packageJson.main;
      const entryFilePath = resolve( `${packageJsonPath}`, entry);
      const projectPath = resolve(__dirname, `../../workspace/project`);
      const projectLibsPath = resolve(projectPath, `./libs/${name}_sys_dist/`);
      console.log('entryFilePath -> ', entryFilePath);
      console.log('projectLibsPath -> ', projectLibsPath);

      const webpackConfigJsCode = `
      const path = require('path');

      module.exports = {
        entry: path.resolve(__dirname, './${entry}'),
        mode: 'production',
        output: {
          path: '${projectLibsPath}',
          filename: '${name}.bundle.js',
          libraryTarget: 'system'
        }
      };`;
      //! 写入 weboack.config.js
      const webpackConfigPath = resolve(packageJsonPath, './webpack.config.js');
      fs.writeFileSync(webpackConfigPath, webpackConfigJsCode, 'utf-8');
       await execSync(`cd ${packageJsonPath} && webpack`);
      // 在project下执行 npm install xxx
      console.log('打包命令执行了 -> ', `cd ${projectPath} && npm install ${name}`);
      const result = await execSync(`cd ${projectPath} && cnpm install ${name}`);
      console.log(result);
      
      // 3. 返回打包后的文件地址
      return result;
    } catch (error) {
      return error;
    }
  }
}
module.exports = new LibraryService();
